const Store = require("electron-store");
const ossManager = require("../aliOssManager");
const Types = require("../../const/eventName");

function getManagerInstance() {
  const settingStore = new Store({ name: "settings" });
  const ossConfig = settingStore.get(Types.OSSCONFIG) || {};
  const enable =
    ossConfig.region &&
    ossConfig.accessKeyId &&
    ossConfig.accessKeySecret &&
    ossConfig.bucket;
  if (enable) {
    return new ossManager(ossConfig);
  } else {
    return null;
  }
}

async function uploadFileToOss(event, filePath) {
  try {
    const client = getManagerInstance();
    const res = await client.uploadFile(filePath);
    event.sender.send(Types.OSSREPLY, res);
  } catch (error) {
    event.sender.send(Types.OSSREPLY, { code: -1 });
  }
}
async function deleteOssFile(event, file) {
  try {
    const client = getManagerInstance();
    const res = await client.deleteFile(file.path);
    event.sender.send(Types.OSSREPLY, res);
  } catch (error) {
    console.log(error);
    event.sender.send(Types.OSSREPLY, { code: -1 });
  }
}

module.exports = {
  uploadFileToOss,
  deleteOssFile,
};
